package org.jeecg.modules.cascv.image.service.merge.ranshaogui;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jeecg.dingtalk.api.core.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.ImageService;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Future;

/**
 * @author
 * @Version 2022/3/21
 * description;
 */
@Service
@Slf4j
public class RanshaoguiService extends ImageService {
    @Value("${imageurl}")
    private  String imageurl;

    @Value("${python.writePicUrl}")
    private String pythonWritePicUrl;

    @Autowired
    private TaskExecutePool taskExecutePool;

    @Override
    public String idsNames() {
        return "TGMTYY1601_09EH_31_HMRCSAPP2,TGMTYY1601_09EH_31_HMRCSAPP3,TGMTYY1601_09EH_31_HMRCSAPP4,6D20H_70H,6D21H_70H,6D22H_70H";
    }

    // Integer width = 1280;
    // Integer height = 1024;
    // 2345的 width = 1296;
    @Override
    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {
        JSONObject conJson = jsonObject.getJSONObject("Content");

        //打印报错不连续的包序号
        String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if(null==lastPackageNum){
            LaptopConstant.packageNumMap.put(key,intpackageNum);
        }else {
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:"+intpackageNum+"，上一包包序号:"+lastPackageNum);
                }
            }
        }

        String secondStr = jsonObject.getString("second");
        long second = Long.parseLong(secondStr);
        String subSecondStr = jsonObject.getString("subsecond");
        secondStr = LaptopUtil.toDayHoursMinSec(second);
        String dataFrames = conJson.getString(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
        String startEndFlag = conJson.getString(LaptopConstant.STARTEND_FLAG_MAP.get(idsName));
        startEndFlag = startEndFlag.split(";")[0];
        dataFrames = (dataFrames.split(";")[1]).substring(2).trim();
       // dataFrames =dataFrames.substring(7,dataFrames.length()-10);
        StringBuilder queue = LaptopConstant.imageData.get(key);
        composite(idsName, key, conJson, dataFrames, queue, startEndFlag, secondStr, subSecondStr);

        return null;
    }

    private boolean composite(String idsName, String key, JSONObject content, String dataFrames, StringBuilder queue, String startEndFlag,String secondStr,String subSecondStr) {
        Integer width = 1296; //1280
        Integer height = 1024;


        if (LaptopConstant.START_FLAG.equalsIgnoreCase(startEndFlag) || !LaptopConstant.END_FLAG.equalsIgnoreCase(startEndFlag)) {
            if (null == queue) {
                queue = new StringBuilder();
                dataFrames = dataFrames.substring(1024*2);
                queue.append(dataFrames);
            } else {
                queue.append(dataFrames);
            }
            LaptopConstant.imageData.put(key, queue);
        } else if (LaptopConstant.END_FLAG.equalsIgnoreCase(startEndFlag)) {
            queue.append(dataFrames);
            //queue = new StringBuilder(queue.substring(0, width * height * 4));

            while (queue.length() < width * height * 4) {
                queue.append("0");
            }
            String imgHexStr = queue.toString();


            CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
                long start = System.currentTimeMillis();
                int[] intBuffer = bayer12(imgHexStr);
            byte[] array = new byte[intBuffer.length];
                    for (int i = 0; i < intBuffer.length; i++) {
                        array[i] = (byte) do16to8(intBuffer[i]);
                    }
                   // byte[] finalArray = array;
                    String idStr = IdWorker.getIdStr();
                    Future<String> submit = LaptopConstant.python_pool.submit(new Callable<String>() {
                        @Override
                        public String call() {
                             Long randomInt = LaptopConstant.python_loop.getAndAdd(1);
                            //                        String postRes = HttpUtil.post(pythonWritePicUrl, HexUtil.encodeHexStr(finalArray) + ",grbg,"+imageExt+"," + height + "," + finalWidth + "," + imageConfig.getBaseDir() + imageSaveDir + "/" + imageSaveName + ",0");
                           // String postRes = HttpUtil.post(pythonWritePicUrl, HexUtil.encodeHexStr(array) + ",grbg," + "png" + "," + height + "," + width + "," + "d:/data/images/"+ idStr + ".png" + ",0");
                            String postRes = HttpUtil.post("http://127.0.0.1:9981", HexUtil.encodeHexStr(array) + ",grbg," + "png" + "," + height + "," + width + "," + "/data/images/"+ idStr + ".png" + ",0");
                            return postRes;
                        }
                    });
            String postRes = null;
            try {
                postRes = submit.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(!StringUtils.equalsIgnoreCase(postRes, "ok")){
                log.error("合成图片失败！" );
                return null;
            }
                    String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr + ".png";
                    //log.info(imageUrl);
                    content.put("imageUrl", imageUrl);
                    content.put("idsName", idsName);
                    //获取时间
                    //     String secondStr = content.getString(LaptopConstant.SECOND_FIELD_MAP.get(idsName)).split(";")[1];
                    //    String subSecondStr = content.getString(LaptopConstant.SUB_SECOND_FIELD_MAP.get(idsName)).split(";")[1];
                    String[] split = secondStr.split(":");
                    content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
                    content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
                    //将图片添加到map
            content.put("key", key);
                log.info("燃烧柜6D20H_70H,6D21H_70H,6D22H_70H 合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");

            return content;
        },taskExecutePool.threadPoolTaskExecutor2());
        LaptopConstant.imageFutureList.add(future);

            LaptopConstant.imageData.remove(key); //清空图片数据


        }

        return true;
    }


    private static int[] bayer12(String a) {
        if (a == null) {
            return null;
        }
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i + 4 <= a.length(); i = i + 4) {
            String partStr = a.substring(i, i + 4);
            char[] aChararr = partStr.toCharArray();
            StringBuilder sb1 = new StringBuilder();
            sb1.append(aChararr[2]);
            sb1.append(aChararr[3]);
            sb1.append(aChararr[0]);
            sb1.append(aChararr[1]);
            list.add(Integer.parseInt(sb1.toString(), 16));
        }
        if (list.size() == 0) {
            return null;
        }
        int[] ints = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            int b = list.get(i);
            ints[i] = b;
        }
        return ints;
    }

    public static int do16to8(int a) {
        double aa = a * 1.0;
        double bb = aa / 65535.0;
        aa = bb * 255.0;
        a = new Double(aa).intValue();
        return a;
    }

    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll");
        List<String> strings = FileUtil.readUtf8Lines("E:\\11图像数据\\cut2\\燃烧\\T20230215202519_0001_009E_F1_00_6DCD_2024_0070_70_6D20.txt");
        RanshaoguiService ranshaoguiService = new RanshaoguiService();

        for (String string : strings) {
            //将str转化为相应的JSONObject对象
            JSONObject jsonObject = JSONObject.parseObject(string);

            ranshaoguiService.merge(jsonObject, "6D20H_70H", "6D20H_70H");
        }

    }

}
